package yl.hs.bmipfull.service.material.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.material.IPurchaseRequireDao;
import yl.hs.bmipfull.pojo.laboratory.TaskConfigDetailsEntity;
import yl.hs.bmipfull.pojo.laboratory.TaskConfigEntity;
import yl.hs.bmipfull.pojo.material.PurchaseRequireDetailsEntity;
import yl.hs.bmipfull.pojo.material.PurchaseRequireEntity;
import yl.hs.bmipfull.pojo.production.ProductionTaskEntity;
import yl.hs.bmipfull.service.laboratory.ITaskConfigDetailsService;
import yl.hs.bmipfull.service.laboratory.ITaskConfigService;
import yl.hs.bmipfull.service.material.IPurchaseRequireDetailsService;
import yl.hs.bmipfull.service.material.IPurchaseRequireService;
import yl.hs.bmipfull.service.production.IProductionTaskService;
import yl.hs.bmipfull.utils.DataState;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 作用:  采购需求信息服务层接口实现<br/>
 * 创建时间: 2021年06月18日 15时13分56秒 <br/>
 *
 * @author 张凯
 */
@Service
public class PurchaseRequireServiceImpl extends PurchaseBaseService implements IPurchaseRequireService {

    @Autowired
    IPurchaseRequireDao dao;
    @Autowired
    ITaskConfigService taskConfigService;

    @Autowired
    ITaskConfigDetailsService configDetailsService;

    @Autowired
    IPurchaseRequireDetailsService detailsService;

    @Autowired
    IProductionTaskService taskService;

    @Override
    public List<PurchaseRequireEntity> queryList(PageQuery pageQuery) throws Exception {
        pageQuery.checkSortSides(PurchaseRequireEntity.class);
        return dao.queryPage(pageQuery.getQuery());
    }

    @Override
    public PageResult<PurchaseRequireEntity> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(PurchaseRequireEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<PurchaseRequireEntity> result = new PageResult(rowNum);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery()));
        result.setPage(page);
        result.setData(dao.queryPage(pageQuery.getQuery()));
        return result;
    }


    @Override
    public PurchaseRequireEntity findBySn(String sn) {
        return dao.findBySN(sn);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer savePurchaseRequire(Map<String, Object> model, String sn) throws Exception {
        Integer result;
        PurchaseRequireEntity entity;
        if (Tl.isEmpty(sn)) {
            //执行保存
            entity = new PurchaseRequireEntity();
            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            entity.setSn(queryNewSN(PurchaseRequireEntity.class));
            result = dao.insertNew(entity);
            if (result > 0) {
                writeLog(ActionType.CREATE, entity.getSn(), "插入采购需求信息信息", Tl.toJson(entity), PurchaseRequireEntity.class);
            }

        } else {
            //执行修改
            entity = findBySn(sn);
            String changeLog = Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            result = dao.update(entity);
            if (result > 0) {
                writeLog(ActionType.UPDATE, sn, "更新采购需求信息信息" + changeLog, Tl.toJson(entity), PurchaseRequireEntity.class);
            }
        }
        if (result > 0) {
            saveGS(
                    entity.getSn(),
                    entity.getRequirFrom(),
                    String.join(",",
                            entity.getRequirFrom(),
                            entity.getDescription()
                    ),
                    entity,
                    HsApp.getCurrent() != null ? HsApp.getCurrent().getUserSN() : null,
                    null
            );
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer delete(String[] sn) {
        Integer result = dao.changeStateBySN(sn, DataState.DELETED.code);
        if (result > 0) {
            writeLog(ActionType.DELETE, sn, PurchaseRequireEntity.class);
            deleteGs(sn);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer createPurchaseRequire(String taskSn) throws Exception {

        Integer result = 0;
        ProductionTaskEntity taskEntity = taskService.findBySn(taskSn);

        String requireSn = queryNewSN(PurchaseRequireEntity.class);
        // TODO:设置采购需求类型和需求来源
        PurchaseRequireEntity purchaseRequire = new PurchaseRequireEntity(requireSn, taskSn, (short) 0,
                "设置配比", "生产任务配比设置完成，需要采购原材", new Date(), new Date(), DataState.CREATED.code);
        result += dao.insertNew(purchaseRequire);

        if (result > 0) {
            //保存采购需求明细信息
            List<TaskConfigEntity> taskConfigList = taskConfigService.queryConfigEntityByTaskSN(taskSn);
            for (TaskConfigEntity taskConfigEntity : taskConfigList) {
                String taskConfigSn = taskConfigEntity.getSn();
                List<TaskConfigDetailsEntity> configDetailsList = configDetailsService.queryByTaskConfigSn(taskConfigSn);
                for (TaskConfigDetailsEntity taskConfigDetails : configDetailsList) {
                    //计算需求数量
                    BigDecimal production = taskConfigDetails.getProduction() != null ? taskConfigDetails.getProduction() : BigDecimal.valueOf(0);
                    BigDecimal quantity = taskEntity.getQuantity() != null ? taskEntity.getQuantity() : BigDecimal.valueOf(0);
                    BigDecimal requireQuantity = production.multiply(quantity);

                    PurchaseRequireDetailsEntity requireDetailsEntity =
                            detailsService.findByRequireSnRmSn(requireSn, taskConfigDetails.getRmSN());
                    if (requireDetailsEntity != null) {
                        detailsService.deleteByRequireSnRmSn(requireSn, taskConfigDetails.getRmSN());
                        requireDetailsEntity.setQuantity(requireDetailsEntity.getQuantity().add(requireQuantity));
                    } else {

                        requireDetailsEntity = new PurchaseRequireDetailsEntity(requireSn, taskConfigDetails.getRmSN(), taskConfigDetails.getRmCate(),
                                taskConfigDetails.getRmName(), taskConfigDetails.getRmSpec(), taskConfigDetails.getBrand(), requireQuantity, "",
                                taskConfigDetails.getSortCode());
                    }

                    result += detailsService.savePurchaseRequireDetails(requireDetailsEntity);


                }
            }
        }
        return result;
    }


}